#!/usr/bin/python

# -*- coding: utf-8 -*-

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or (at
#  your option) any later version.
#
#  This program is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


import sys
import math
from qt import *
import time
import os
import codecs

#
# in savepart.py there are all classes which are used to save the data
# 
# Classes: 	saveClass:	the functions defined in here are called from outside
#

class saveClass(QWidget):
	def __init__(self,parent):
        	QWidget.__init__(self,parent)
		selfLayout = QGridLayout(self,1,1,11,6,"saveClass")

		self.groupBox = QGroupBox(self,"groupBox1")
		self.groupBox.setTitle("Save to...")
        	self.groupBox.setColumnLayout(0,Qt.Vertical)
        	#selfLayout.layout().setSpacing(3) #6)
        	#selfLayout.layout().setMargin(8)
        	groupBoxLayout = QGridLayout(self.groupBox.layout())
        	groupBoxLayout.setAlignment(Qt.AlignTop)		
		
		self.datei = QLineEdit(self.groupBox,'temp')
		self.datei.setText('test/temp')
		QToolTip.add( self.datei, "Data will be saved in this file (added by -001, -002, etc.)")
		self.speichernlabel = QLabel(self.groupBox)
		self.speichernlabel.setText("Save to (base-)file:")
		
		self.dateiendung=QComboBox(self.groupBox)
		self.dateiendung.setEditable(True)
		self.dateiendung.insertItem("")
		self.dateiendung.insertItem(".dat")
		self.dateiendung.insertItem(".txt")
		self.dateiendung.insertItem(".csv")
		self.dateiendung.setFixedWidth( self.dateiendung.sizeHint().width() )
		self.dateiendung.setCurrentItem(1)
		QToolTip.add( self.dateiendung, "Add this file extension to the saved file")
		
		self.speichernbutton = QPushButton('Choose (base-)file',self.groupBox)
		
        	#self.speichern = QHBoxLayout(self)
		groupBoxLayout.addWidget(self.speichernlabel,0,0)
		groupBoxLayout.addWidget(self.datei,0,1)
		groupBoxLayout.addWidget(self.dateiendung,0,2)
        	groupBoxLayout.addWidget(self.speichernbutton,0,3)
        	groupBoxLayout.layout().setSpacing(3) #6)
        	groupBoxLayout.layout().setMargin(0)		
		self.connect(self.speichernbutton,SIGNAL('clicked()'),self.verzeichnis)
		
		selfLayout.addWidget(self.groupBox,0,0)
	        #self.clearForm1Layout = QGridLayout(self,1,1,11,6,"Form1Layout")
		self.counter=0
		
	def verzeichnis(self):
		s = QFileDialog.getSaveFileName("","All File (*.*)",self,"File To Save","File To Save" )
		if len(s)>0:
			self.datei.setText(s)
		

	def endMessung(self):
		print "endMessung"
		self.emit(PYSIGNAL("reqMessdaten"),())
	
	
	def getFileName(self):
		count=unicode(self.counter)
		while len(count)<3: 
			count="0"+count
		dateiname=unicode(self.datei.text())+"-"+count+unicode(self.dateiendung.currentText())
		return dateiname

	def nextData(self,daten):
		test=os.path.split(unicode(self.datei.text()))
		if (os.path.isdir(test[0])==False)and(test[0]!=""):
			newDir=QDir()
			if newDir.mkdir(test[0])==False:
				QMessageBox.critical( self, "pyvLab", "ERROR: Directory to save in does not exist. Data will be saved in program directory in a file called \"nodir-xxx\".")
				self.datei.setText("nodir")		
		
		fn=unicode(self.datei.text())+".tmp"
		#f=open(fn, 'a')
		f=codecs.open(fn, encoding='utf-8', mode='a+')
		for zeile in daten:
			#print zeile
			f.write(unicode(QString(zeile))+"\n")
		f.close()
			
	def speichere(self,daten,head):
		#print "speichere"
		test=os.path.split(unicode(self.datei.text()))
		if (os.path.isdir(test[0])==False)and(test[0]!=""):
			newDir=QDir()
			if newDir.mkdir(test[0])==False:
				QMessageBox.critical( self, "pyvLab", "ERROR: Directory to save in does not exist. Data will be saved in program directory in a file called \"nodir-xxx\".")
				self.datei.setText("nodir")		
	
		
		fi=QFileInfo()
		fi.setFile(self.getFileName())
		while (fi.exists()==True):
			self.counter+=1
			fi.setFile(self.getFileName())

		fn=self.getFileName()
		#f=open(fn, 'w')
		f=codecs.open(fn, encoding='utf-8', mode='w+')
		f.write(daten)
		f.close()
		
		self.emit(PYSIGNAL('dataSaved'),(unicode(fi.fileName()),))
		
		#Single Plot-output
		#f=open(unicode(self.datei.text())+".gnuplot", 'a')
		f=codecs.open(unicode(self.datei.text())+".gnuplot", encoding='utf-8', mode='a')
		title="Plot of "+fn+"\\n"
		for x in head:
			title=title+"\\n"+(unicode(QString(x))[1:]).strip()
		
		plotfile=QFileInfo(fn)
		
		daten="\nset terminal png\nset title \""+title+"\" \n"
		daten=daten+"set output \""+unicode(plotfile.fileName())+".png\" \n"
		daten=daten+"plot \""+unicode(plotfile.fileName())+"\" with lines\n\n"
		f.write(daten)
		f.close()
		
		#All Measurements in One Outputfile
		fi=QFileInfo(unicode(self.datei.text())+"-allinone.gnuplot")
		allinOnefileExists=fi.exists()
		f=codecs.open(unicode(self.datei.text())+"-allinone.gnuplot", encoding='utf-8', mode='a')
		plotfile=QFileInfo(fn)
		if allinOnefileExists==False:
			daten="\nset terminal png\nset title \""+unicode(self.datei.text())+"\" \n"
			daten=daten+"set output \""+unicode(plotfile.fileName())+"-allinone.png\" \n"
			f.write(daten)
			f.write("plot \""+unicode(plotfile.fileName())+"\" title \""+unicode(plotfile.fileName())+"\" with lines")
		else:
			f.write(",\\\n \""+unicode(plotfile.fileName())+"\" title \""+unicode(plotfile.fileName())+"\" with lines")
		f.close()		
		
		fn=unicode(self.datei.text())+".tmp"
		f=open(fn, 'w')
		f.write("#Tempfile with measurement data of the current measurement (backup)\n")
		f.close()		
		
		return True

		
		
		
		
		
		
